package cloud.maque.sso.client.Interceptors;

import cloud.maque.common.core.exceptions.BusinessException;
import cloud.maque.sso.client.annotations.TempToken;
import cn.dev33.satoken.temp.SaTempUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.reflect.Method;

/**
 * 临时Token拦截器
 */
public class TempTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            // 检查方法上是否有特定的注解
            if (method.isAnnotationPresent(TempToken.class)) {
                // 如果有，继续判断临时Token是否有效
                if (request.getParameter("token") == null) {
                    response.setContentType("application/json;charset=UTF-8");
                    response.getWriter().write("{\"code\":401,\"msg\":\"临时Token无效\"}");
                    return false;
                } else {
                    String token = request.getParameter("token");
                    //验证临时的Token
                    String value = SaTempUtil.parseToken(token, String.class);
                    if (value == null) {
                        response.setContentType("application/json;charset=UTF-8");
                        response.getWriter().write("{\"code\":401,\"msg\":\"临时Token无效\"}");
                        return false;
                    }
                }
                return true;
            }
        }
        return true;
    }
}